const FUN = require('../comm/func');
const rCache = require('../model/redis_cache');
const timLib = require('../comm/time-lib');
const mbLib = require('../comm/modbus-lib');
const PMR=require('../utils/policyManger');
const devManger = require('../utils/devManger');

module.exports = class Tim_Mq
{
  //将数据库选项缓存到redis
  //policy 来自数据库的记录，附加了user_auth,user_level字段
  //opts 数据库json字段的解析对象
  //CacheCallback 存储执行函数
  static InitCache(policy,opts,CacheCallback)
  {
    if(FUN.isLocal()) return false;//不允许本地运行

    let obj=PMR.baseParam(policy);//即将缓存到redis的参数

    //检查json选项
    if( parseInt(opts.period)==0 || opts.data.length==0 )
    {
      console.error('wrong Tim_Mq params',policy.id);
      return false;
    }

    //json options参数存储
    if (policy._user_level == 0)
      obj.period = parseInt(opts.period)*60;//周期
    else
      obj.period = opts.period;//周期

    opts.data = opts.data.replace(/[\n]/g,'');//去掉换行
    opts.data = opts.data.replace(/[;]$/g,'');//去掉末尾分号
    obj.data = opts.data;//数据

    //缓存参数
    obj.hwid = policy.master;
    obj.hwtype = FUN.Hwid2TypeName(policy.master);
    obj.topic = '0/'+obj.hwtype+'/tx/'+obj.hwid;
    obj.tail_delay = opts.tail_delay;
    CacheCallback(policy.id,policy.master,obj);//记录到缓存

    rCache.setKey(PMR.rdNode(obj),'count',0,86400);

    //开启定时器
    PMR.setSecInter(obj.policy_id,obj.period,opts.delay);
  }//end InitCache

  //处理数据
  // topic = {project,devType,func,devId}
  // dConf即InitCache中的obj
  // dataBuf即mq消息内容，buf对象
  static async DataIn(topic,dConf,DataBuf)
  {
    return;
  }

  //周期回调
  static SecInter(dConf,nowStamp)
  {
    //pcyLog('[%d] tim-mq exp',dConf.policy_id);
    rCache.getKey(PMR.rdNode(dConf),'count').then(count=>{
      let data=dConf.data.split(';');
      let n=count%data.length;

      if(data && data[n])
      {
        let dArray=data[n].split(' ');
        let sendArray=[];

        for(let c of dArray)
        {
          if(c=='#c')
          {
            let crc=mbLib.crc16(sendArray);
            sendArray.push(crc>>8);
            sendArray.push(crc&0xff);
          }
          else
          {
            if(!isNaN(parseInt(c,16)))
              sendArray.push(parseInt(c,16));
          }
        }

        PMR.mqPub(dConf.topic,Buffer.from(sendArray));
      }

      if(n==(data.length-1)) PMR.setSecInter(dConf.policy_id,parseInt(dConf.tail_delay)?dConf.tail_delay:dConf.period);//大周期定时
      else if(n==0) PMR.setSecInter(dConf.policy_id,dConf.period);

      rCache.incKey(PMR.rdNode(dConf),'count',86400);
    })
  }//end function



}